<template>
  <div class="product-detail-page">
    <!-- 页面标题和操作按钮 -->
    <div class="header-bar">
      <h2>商品详情</h2>
      <div class="action-buttons">
        <!-- <el-button type="primary" icon="el-icon-edit" @click="editProduct">编辑</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="deleteProduct">删除</el-button> -->
        <el-button type="default" icon="el-icon-arrow-left" @click="goBack">返回</el-button>
      </div>
    </div>

    <!-- 商品信息主内容 -->
    <el-row :gutter="20" class="product-content">
      <!-- 左侧：商品图片轮播 -->
      <el-col :span="8" class="product-images">
        <el-carousel height="400px" indicator-position="outside">
          <el-carousel-item v-for="(pic, index) in images" :key="index">
            <img :src="pic" alt="商品图片" class="image-carousel">
          </el-carousel-item>
        </el-carousel>
      </el-col>

      <!-- 右侧：商品基本信息 -->
      <el-col :span="16" class="product-info">
        <h3 class="product-title">{{ product.name }}</h3>
        <ul class="info-list">
          <li><strong>品牌：</strong>{{ product.brandName }}</li>
          <li><strong>地区：</strong>{{ product.regionName }}</li>
          <li><strong>价格：</strong><span class="price">{{ product.price }} 元</span></li>
          <li><strong>促销价：</strong><span class="promotion-price">{{ product.promotionPrice }} 元</span></li>
          <li><strong>库存：</strong>{{ product.stock }}</li>
          <li><strong>状态：</strong>{{ product.status === 1 ? '上架' : '下架' }}</li>
          <li><strong>赠送积分：</strong>{{ product.giftPoint }}</li>
          <li><strong>描述：</strong>{{ product.description }}</li>
        </ul>
      </el-col>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="tabs-container">
      <!-- SKU 列表 -->
      <el-tab-pane label="SKU 列表" name="skuList" style="width: 100%;">

        <el-table :data="skuData.tableData" style="width: 100%">
          <el-table-column v-for="column in skuData.columns" :key="column.prop" :label="column.label"
                           :prop="column.prop">
            <template slot-scope="scope">
              <el-input v-model="scope.row[column.prop]" :disabled="true" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>

      <!-- 商品详情 -->
      <el-tab-pane label="商品详情" name="productDetails">
        <div class="product-description" v-html="product.productHtml"></div>
      </el-tab-pane>

      <!-- 其他信息 -->
      <el-tab-pane label="其他信息" name="otherInfo">
        <p><strong>服务保障：</strong>
          <span v-for="(item,index) in serviceIds" :key="index">
            <span v-if="item === 1" style="margin: 0 5px">无忧退货</span>
            <span v-else-if="item === 2" style="margin: 0 5px">快速退款</span>
            <span v-else-if="item === 3" style="margin: 0 5px">免费包邮</span>
          </span>
        </p>
        <p><strong>创建时间：</strong>{{ product.createTime }}</p>
        <p><strong>更新时间：</strong>{{ product.updateTime }}</p>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {getProduct} from "@/api/shopping/product";

export default {
  name: "ProductDetailPage",
  data() {
    return {
      product: {}, // 商品详情
      activeTab: "skuList", // 当前选中的标签
      images: [], // 商品图片
      serviceIds: [],
      skuData: {
        columns: [],
        tableData: [],
      },
    };
  },
  mounted() {
    if (this.$route.query.id) {
      this.fetchProductDetails(this.$route.query.id);
    }
  },
  methods: {
       uniqueKeys(data) {
      const keysSet = new Set();
      data.forEach(item => {
        keysSet.add(item.key);
      });
      return Array.from(keysSet);
    },
    transformData(row) {
      const excludeKeys = ['promotionPrice', 'salePrice', 'stock', 'warningStock'];
      const result = [];
      for (const key in row) {
        if (row.hasOwnProperty(key) && !excludeKeys.includes(key)) {
          result.push({key, value: row[key]});
        }
      }
      return result;
    },
    deTransformData(data) {
      const result = {};
      for (const item of data) {
        result[item.key] = item.value;
      }
      return result;
    },
    // 获取商品详情`
    async fetchProductDetails(id) {
      const res = await getProduct(id);
      if (res.code === 200) {
        this.product = res.data;
        this.serviceIds = res.data.serviceIds.split(",").map(Number);
        this.images = res.data.albumPics.split(",");
         let defaultCol = [{label: '销售价格', prop: 'salePrice'},
            {label: '促销价格', prop: 'promotionPrice'},
            {label: '商品库存', prop: 'stock'},
            {label: '库存预警值', prop: 'warningStock'}]
          //转json
          let skuList = [];
          res.data.skuList.forEach(item => {
            skuList.push(...JSON.parse(item.spData))
          })
          let key = this.uniqueKeys(skuList)
          let newCol = key.map(item => {
            return {label: item, prop: item}
          })
          this.skuData.columns = [...newCol, ...defaultCol]
          //处理table数据
          res.data.skuList.forEach(item => {
            let obj = {
              salePrice: item.price,
              promotionPrice: item.promotionPrice,
              stock: item.stock,
              warningStock: item.warningStock
            }
            let skuAttr = this.deTransformData(JSON.parse(item.spData))
            //合并
            obj = {...obj, ...skuAttr}
            this.skuData.tableData.push(obj)
          })
      }
    },
    editProduct() {
      this.$router.push({path: "/product/edit", query: {id: this.$route.query.id}});
    },
    deleteProduct() {
      this.$confirm("确认删除该商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log("删除商品");
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>

<style scoped>
/* 页面整体样式 */
.product-detail-page {
  padding: 20px;
  background-color: #f4f5f7;
  min-height: 100vh;
}

/* 顶部标题栏 */
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-bar h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.action-buttons .el-button {
  margin-left: 10px;
}

/* 主内容布局 */
.product-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.product-images .image-carousel {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  margin-bottom: 10px;
  font-size: 14px;
  line-height: 1.8;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.promotion-price {
  color: #67c23a;
  font-weight: bold;
}

/* 标签页 */
.tabs-container {
  margin-top: 20px;
}

.sku-table .spec-tag {
  display: inline-block;
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
  margin-right: 5px;
}
/deep/ img{
  width: 100%!important;
  height: 100%!important;
}
</style>
